#!/bin/bash


# Variable for displaying log
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
MAGENTA=$(tput setaf 5)
NC=$(tput sgr0)
BOLD=$(tput bold)
INFO=$(tput setaf 3)


cur_path="$(pwd)"
FILE_NAME=$0
json_file=""
goproxy_array1=("IEdgeInsights/EtcdUI/Dockerfile", "IEdgeInsights/OpcuaExport/Dockerfile", "IEdgeInsights/Telegraf/Dockerfile")
goproxy_array2=("IEdgeInsights/RestDataExport/Dockerfile", "IEdgeInsights/InfluxDBConnector/Dockerfile", "IEdgeInsights/ImageStore/Dockerfile")



Usage()
{
    echo
	echo "${BOLD}${INFO}==================================================================================${NC}"
    echo
	echo "${BOLD}${GREEN}Usage :: $0 [OPTION...] ${NC}"
    echo
	echo "${INFO}List of available options..."
    echo
	echo "${INFO}Please put this script in the same level directory of folder IEdgeInsights"
    echo
	echo "${INFO}<your_config.json>	json file,include info that you want to replace in dir named IEdgeInsights"
    echo
	echo "${INFO}--help		display this help and exit"${NC}
    echo
	echo "${INFO}-h		    display this help and exit"${NC}
    echo
	echo "${BOLD}${MAGENTA}

		- RUNS SAMPLE
		$FILE_NAME eii-prc-source-[version].json
	"
	echo "${INFO}===================================================================================${NC}"
	exit 1
}


parse_commandLine_args()
{
	if [ $# == "0" ];then
		return;
	fi

	# echo "${INFO}Reading the command line args...${NC}"
	for ARGUMENT in "$@"
	do
	    KEY=$(echo $ARGUMENT)

	    case "$KEY" in
		    *.json) json_file=$ARGUMENT ;;
		    --help) Usage ;;
            -h) Usage ;;
		     *) echo "${RED}Invalid arguments passed..${NC}"; Usage; ;;
	    esac
	done
}


parse_json(){
    for ((i=0;i<$keys_lenth;i++));
    do
        key=$(echo $json_list | jq .[$i].key)
        key=$(echo $key | sed 's/\"//g')
        if [ -f "$cur_path/$key" ];then
            value=$(echo $json_list | jq .[$i].value)
            sublenth=$(echo $value | jq -r keys[] | wc -l)
                for ((j=0;j<$sublenth;j++));
                do
                subkey=$(echo $value | jq -r to_entries | jq .[$j].key)
                subvalue=$(echo $value | jq -r to_entries | jq .[$j].value)
                subkey=$(echo $subkey | sed 's/\"//g')
                subvalue=$(echo $subvalue | sed 's/\"//g')
                set -x
                sed -i "s!$subkey!$subvalue!g" $cur_path/$key
                set +x
                done
        elif [ -d "$cur_path/$key" ];then
            echo $cur_path/$key
            file_key=$(echo $json_list | jq .[$i].value | jq -r keys[])
            value=$(echo $json_list | jq .[$i].value | jq -r ".$file_key")
            sublenth=$(echo $value | jq -r keys[] | wc -l)
            for ((j=0;j<$sublenth;j++));
                    do
                subkey=$(echo $value | jq -r to_entries | jq .[$j].key)
                            subvalue=$(echo $value | jq -r to_entries | jq .[$j].value)
                            subkey=$(echo $subkey | sed 's/\"//g')
                            subvalue=$(echo $subvalue | sed 's/\"//g')
                set -x
                find $cur_path/$key -type f -name "$file_key" | xargs sed -i "s!$subkey!$subvalue!g"
                set +x
            done

        elif [[ $key == *goproxy* ]];then
            value=$(echo $json_list | jq .[$i].value)
            sublenth=$(echo $value | jq length)
            for ((j=0;j<$sublenth;j++));
                    do
                            subkey=$(echo $value | jq .[$j] | jq -r keys)
                            subvalue=$(echo $value | jq .[$j] | jq ".$subkey")
                            subkey=$(echo $value | jq .[$j] | jq -r keys[] | sed 's/\"//g')
                            subvalue=$(echo $subvalue | sed 's/\"//g')
                spec_line=`cat "$cur_path/$subkey" | grep -n "$subvalue" | awk -F ":" '{print $1}'`

		if echo "${goproxy_array1[@]}" | grep -w $subkey &>/dev/null; then
                	add_line=$(( $spec_line-1 ))
		elif echo "${goproxy_array2[@]}" | grep -w $subkey &>/dev/null; then
			add_line=$(( $spec_line-2 ))
		fi
		if [[ $subkey == "IEdgeInsights/Telegraf/Dockerfile" ]];then
			key=${key/io/cn}
		fi

                set -x
                sed -i "$add_line i ENV GOPROXY $key" "$cur_path/$subkey"
                set +x
                    done

        elif [[ $key == *apt-source* ]];then
            value=$(echo $json_list | jq .[$i].value)
            sublenth=$(echo $value | jq length)
	    cat > apt_cn.txt <<EOF
RUN sed -i 's!http://security.ubuntu.com/ubuntu!https://mirrors.tuna.tsinghua.edu.cn/ubuntu!g' /etc/apt/sources.list
RUN sed -i 's!http://archive.ubuntu.com/ubuntu!https://mirrors.tuna.tsinghua.edu.cn/ubuntu!g' /etc/apt/sources.list
RUN apt-get update && apt-get install -y ca-certificates
# update the apt source
EOF
            for ((j=0;j<$sublenth;j++));
                    do
                            subkey=$(echo $value | jq .[$j] | jq -r keys)
                            subvalue=$(echo $value | jq .[$j] | jq ".$subkey")
                            subkey=$(echo $value | jq .[$j] | jq -r keys[] | sed 's/\"//g')
                            subvalue=$(echo $subvalue | sed 's/\"//g')
			    spec_line=`cat "$cur_path/$subkey" | grep -n "$subvalue" | awk -F ":" '{print $1}'`
			    for de_line in `echo $spec_line`; do
				    add_line=$(( $de_line-1 ))
				    cat apt_cn.txt | while read line
			    	    do
					set -x
					echo $line | sed -i "$add_line i $line" "$cur_path/$subkey"
					set +x
				    done
			    done
		    done
	    rm -rf apt_cn.txt



        else
            value=$(echo $json_list | jq .[$i].value)
            subkey=$(echo $value | jq -r keys)
            subvalue=$(echo $value | jq ".$subkey")
            subkey=$(echo $value | jq -r keys[] | sed 's/\"//g')
            subvalue=$(echo $subvalue | sed 's/\"//g')
            set -x
            grep -nr "$key" | awk -F ":" '{print$1}' | xargs sed -i "s!$subkey!$subvalue!g"
            set +x


        fi

    done
}


if [ $# -ne "0" ];then
	parse_commandLine_args "$@"
fi

sudo apt-get install -y jq
# add pip source
grep -nr "install.* -r .*requirements.txt" | grep -i IEdgeInsights | grep -v README | awk -F ":" '{print$1}' | xargs sed -i 's!install.* -r .*requirements.txt!& -i https://mirrors.aliyun.com/pypi/simple!g'
grep -nr "pip install -U pip" | grep -i IEdgeInsights | grep -v README | awk -F ":" '{print$1}' | xargs sed -i 's!pip install -U pip!& -i https://mirrors.aliyun.com/pypi/simple!g'

json_list=$(cat $json_file | jq -r to_entries)
keys_lenth=$(jq -r keys[] $json_file | wc -l)
parse_json

